import { NextFunction, Request, Response } from "express";
import * as userService from './user.service'

export const store=async(request:Request,response:Response,next:NextFunction)=>{
    // console.log(request.body)
    // 中间件和controller的使命
    // 中间件是node的开发特色
    const {name,password} = request.body
    
    try {
        const data = await userService.createUser({name,password})
        response.status(201).send(data)  // 201 Created 已创建
    } catch (error) {
        next(error)
    }
}

export const show=async(request:Request,response:Response,next:NextFunction)=>{
    const {userId}=request.params
    try {
        const user=await userService.getUserById(parseInt(userId,10))
        if(!user){
            return next(new Error('USER_NOT_FOUND'))
        }
        response.send(user)
    } catch (error) {
        next(error)
    }
}

export const update = async (request:Request,response:Response,next:NextFunction)=>{
    const {id} = request.user
    const {name,password} = request.body.update
    // console.log(name,password)
    try {
        const data = await userService.updataUser(id,{name,password})
        response.send(data)
    } catch (error) {
        next(error)
    }
}